package spravaZamestnancov;

import importExportDat.ImportExportCSV;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import strukturaZamestnanciNepritomnost.Zamestnanci;
import strukturaZamestnanciNepritomnost.Zamestnanec;

/**
 *
 * @author Monika
 */
public class SpravaZamestnancov extends javax.swing.JFrame {

    /**
     * Creates new form SpravaZamestnancov
     */
    private TreeMap<Integer, Zamestnanec> zamestnanciZoznam;
    private TreeMap<Integer, Integer> prvkyTabulkyID; //mapuje poziciu v tabulke na id zamestnanca
    private Zamestnanci zamestnanci;
    private ImportExportCSV ie;
    private myDefaultTableModel dtm;
    PridatZamestnanca pz;
    private final int stlpecVymaz = 3;

    private class myDefaultTableModel extends DefaultTableModel { //model pre tabulku zamestnancov

        @Override   //aby v danom stlpci boli checkboxy
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == stlpecVymaz) {
                return Boolean.class;
            } else {
                // returns Object.class  
                return super.getColumnClass(columnIndex);
            }
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return ((column == 3) || (column == 4));
        }
    }

    private class ButtonRenderer extends JButton implements TableCellRenderer {
        //pre zobrazenie buttonov v poslednom stlpci tabulky

        public ButtonRenderer() {
            setOpaque(true);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(UIManager.getColor("Button.background"));
            }
            setText((value == null) ? "" : value.toString());
            return this;
        }
    }

    private class ButtonEditor extends DefaultCellEditor {

        protected JButton button;
        private String label;
        private boolean isPushed;
        private int row;

        public ButtonEditor(JCheckBox checkBox) {
            super(checkBox);
            button = new JButton();
            button.setOpaque(true);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    fireEditingStopped();
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            if (isSelected) {
                button.setForeground(table.getSelectionForeground());
                button.setBackground(table.getSelectionBackground());
            } else {
                button.setForeground(table.getForeground());
                button.setBackground(table.getBackground());
            }
            label = (value == null) ? "" : value.toString();
            button.setText(label);
            isPushed = true;
            this.row = row;
            return button;
        }

        @Override
        public Object getCellEditorValue() {
            if (isPushed) {
                // 
                int id = prvkyTabulkyID.get(row);
                EditZamestnanec ez = new EditZamestnanec(id);
                ez.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                ez.setVisible(true);
                ez.addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosed(WindowEvent e) {
                        try {
                            zamestnanci = new Zamestnanci();
                            refreshTable();
                        } catch (SQLException ex) {
                            Logger.getLogger(SpravaZamestnancov.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (ParseException ex) {
                            Logger.getLogger(SpravaZamestnancov.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                });
            }
            isPushed = false;
            return label;
        }

        @Override
        public boolean stopCellEditing() {
            isPushed = false;
            return super.stopCellEditing();
        }

        @Override
        protected void fireEditingStopped() {
            super.fireEditingStopped();
        }
    }

    public SpravaZamestnancov() {
        initComponents();

        //centralizovanie okna
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int X = (screen.width / 2) - (this.getWidth() / 2); // Center horizontally.
        int Y = (screen.height / 2) - (this.getHeight() / 2); // Center vertically.
        this.setLocation(X, Y);

        try {
            zamestnanci = new Zamestnanci();
        } catch (SQLException ex) {
            Logger.getLogger(SpravaZamestnancov.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Nepodarilo sa načítať zamestnancov z databázy!", "Chyba", JOptionPane.ERROR_MESSAGE);
        } catch (ParseException ex) {
            Logger.getLogger(SpravaZamestnancov.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Nepodarilo sa načítať zamestnancov z databázy!", "Chyba", JOptionPane.ERROR_MESSAGE);
        }
        ie = new ImportExportCSV();

        dtm = new myDefaultTableModel();
        String headers[] = new String[5];
        headers[0] = "ID";
        headers[1] = "Meno";
        headers[2] = "Priezvisko";
        headers[3] = "Odstránenie";
        headers[4] = "Upraviť";
        dtm.setColumnIdentifiers(headers);
        dtm.getColumnClass(2);

        prvkyTabulkyID = new TreeMap<>();

        if (getZamestnanci()) {
            int j = 0;
            for (int i : zamestnanciZoznam.keySet()) {
                dtm.addRow(new Object[]{i, zamestnanciZoznam.get(i).getMeno(), zamestnanciZoznam.get(i).getPriezvisko(), false, "Upraviť"});
                prvkyTabulkyID.put(j, i);
                j++;
            }
        }

        zamestnanciTable.setModel(dtm);
        zamestnanciTable.getColumn("Upraviť").setCellRenderer(new ButtonRenderer());
        zamestnanciTable.getColumn("Upraviť").setCellEditor(new ButtonEditor(new JCheckBox()));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        zamestnanciTable = new javax.swing.JTable();
        removeButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        importButton = new javax.swing.JButton();
        exportButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Zamestnanci");

        zamestnanciTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(zamestnanciTable);

        removeButton.setText("Odstrániť");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        addButton.setText("Pridať zamestnanca");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        importButton.setText("Import");
        importButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importButtonActionPerformed(evt);
            }
        });

        exportButton.setText("Export");
        exportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addButton)
                        .addGap(45, 45, 45)
                        .addComponent(importButton)
                        .addGap(18, 18, 18)
                        .addComponent(exportButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(removeButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 528, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(24, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(removeButton)
                    .addComponent(addButton)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(importButton)
                        .addComponent(exportButton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        // odstranenie zvolenych zamestnancov z tabulky
        ArrayList<Integer> indexyVymazat = new ArrayList<>();
        for (int i = 0; i < dtm.getRowCount(); i++) {
            if (dtm.getValueAt(i, stlpecVymaz) == true) {
                indexyVymazat.add(prvkyTabulkyID.get(i));
            }
        }
        if (!indexyVymazat.isEmpty()) {
            try {
                removeZamestnanci(indexyVymazat);
            } catch (SQLException ex) {
                Logger.getLogger(SpravaZamestnancov.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this, "Nepodarilo sa odstrániť zamestnancov!", "Chyba", JOptionPane.ERROR_MESSAGE);
            }
            refreshTable();
        }
    }//GEN-LAST:event_removeButtonActionPerformed

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        // pridanie zamestnanca, vytvori nove okno
        pz = new PridatZamestnanca(zamestnanci);
        pz.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pz.setVisible(true);
        pz.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                refreshTable();
            }
        });
    }//GEN-LAST:event_addButtonActionPerformed

    private void importButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importButtonActionPerformed

        // import zamestnancov, vyber suboru pre import

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        chooser.setSelectedFile(new File("subor_so_zamestnancami.csv"));
        chooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".csv") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "CSV Files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r == JFileChooser.APPROVE_OPTION) {
            String csvname = chooser.getSelectedFile().getPath();
            ImportExportCSV importexport = new ImportExportCSV(this);
            boolean importZamestnanci = false;
            try {
                importZamestnanci = importexport.importZamestnanci(csvname);
            } catch (SQLException | ParseException ex) {
                Logger.getLogger(SpravaZamestnancov.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (importZamestnanci == false) {
                JOptionPane.showMessageDialog(this, "Nepodarilo sa načítať zamestnancov !", "Chyba", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Zamestnanci sa uspesne nacitali.", "Info", JOptionPane.INFORMATION_MESSAGE);
            }
        }
        refreshTable();
    }//GEN-LAST:event_importButtonActionPerformed

    private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed

        // export zoznamu zamestnancov, zvolenie suboru pre export
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        chooser.setSelectedFile(new File("zamestnanci.csv"));
        chooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".csv") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "CSV Files";
            }
        });
        int r = chooser.showSaveDialog(this);
        if (r == JFileChooser.APPROVE_OPTION) {
            String csvname = chooser.getSelectedFile().getPath();
            if (!csvname.endsWith(".csv")) {
                csvname += ".csv";
            }
            // ak existuje uz taky file, upozorni uzivatela
            boolean exists = (new File(csvname)).exists();
            if (exists) {
                int volba = JOptionPane.showConfirmDialog(this, "Rovnaký súbor už existuje, prajete si ho prepísať?.", "Info", JOptionPane.YES_NO_OPTION);
                if (volba == JOptionPane.NO_OPTION) {
                    return;
                }
            }
            ImportExportCSV importexport = new ImportExportCSV(this);
            boolean exportZamestnanci = importexport.exportZamestnanci(csvname, zamestnanciZoznam);
            if (!exportZamestnanci) {
                JOptionPane.showMessageDialog(this, "Nepodarilo sa exportvoat zamestnancov.", "Chyba", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Export zamestnancov prebehol uspesne.", "Info", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }//GEN-LAST:event_exportButtonActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SpravaZamestnancov.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SpravaZamestnancov.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SpravaZamestnancov.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SpravaZamestnancov.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SpravaZamestnancov().setVisible(true);
            }
        });
    }

    public void refreshTable() {
        /**
         * Obnovenie tabuľky zamestnancov.
         */
        if (getZamestnanci()) {
            dtm.setRowCount(0);

            int j = 0;
            for (int i : zamestnanciZoznam.keySet()) {
                dtm.addRow(new Object[]{i, zamestnanciZoznam.get(i).getMeno(), zamestnanciZoznam.get(i).getPriezvisko(), false, "Upraviť"});
                prvkyTabulkyID.put(j, i);
                j++;
            }
        }
    }

    private boolean getZamestnanci() {
        /**
         * Získa z databázy všetkých zamestnancov a uloží ich do premennej
         * zamestnanciZoznam
         */
        
        if (zamestnanci.isConnected()) {
            zamestnanciZoznam = zamestnanci.getZamestnanciActive();
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "Nepodarilo sa načítať zamestnancov z databázy!", "Chyba", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    private void removeZamestnanci(ArrayList<Integer> zamIndex) throws SQLException {
        /**
         * Odstráni zoznam zamestnancov postupne z databázy.
         *
         * @param zamIndex zoznam zamestnancov
         */
        for (int i = zamIndex.size()-1; i>=0; i--) {
            zamestnanci.removeZamestnanec(zamIndex.get(i));
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton exportButton;
    private javax.swing.JButton importButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton removeButton;
    private javax.swing.JTable zamestnanciTable;
    // End of variables declaration//GEN-END:variables
}
